<template>
  <div class="approval-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>待审批列表</h3>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-form-container">
        <el-form :model="searchForm" class="search-form">
          <div class="form-row">
            <el-form-item label="物品名称">
              <el-input v-model="searchForm.itemName" placeholder="请输入物品名称" clearable />
            </el-form-item>
            <el-form-item label="申请人">
              <el-input v-model="searchForm.requesterName" placeholder="请输入申请人" clearable />
            </el-form-item>
            <el-form-item label="申请日期">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="date-picker"
              />
            </el-form-item>
            <el-form-item class="button-item">
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      
      <!-- 列表 -->
      <el-table
        v-loading="loading"
        :data="pendingRequests"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="编号" width="80" />
        <el-table-column prop="itemName" label="物品名称" min-width="120" />
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="budget" label="预算" width="100">
          <template #default="scope">
            ¥{{ scope.row.budget.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="申请人" width="120">
          <template #default="scope">
            {{ scope.row.requesterName || (scope.row.requestUser ? scope.row.requestUser.name : '未知') }}
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="申请理由" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="申请日期" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click="viewDetail(scope.row.id)"
            >
              查看
            </el-button>
            <el-button 
              link 
              type="success" 
              @click="handleApproval(scope.row, 'APPROVED')"
            >
              通过
            </el-button>
            <el-button 
              link 
              type="danger" 
              @click="handleApproval(scope.row, 'REJECTED')"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialog.visible"
      :title="approvalDialog.type === 'APPROVED' ? '通过申请' : '拒绝申请'"
      width="500px"
    >
      <el-form 
        :model="approvalForm" 
        :rules="approvalRules"
        ref="approvalFormRef"
        label-width="80px"
      >
        <el-form-item 
          label="审批意见" 
          prop="comment"
          :rules="[
            { 
              required: approvalDialog.type === 'REJECTED', 
              message: '拒绝申请时必须填写审批意见', 
              trigger: 'blur' 
            }
          ]"
        >
          <el-input
            v-model="approvalForm.comment"
            type="textarea"
            rows="4"
            :placeholder="approvalDialog.type === 'REJECTED' ? '请输入拒绝理由（必填）' : '请输入审批意见（选填）'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approvalDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitApproval" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPendingPurchaseRequests, approvePurchaseRequest } from '@/api/purchase-request'
import { formatDateTime } from '@/utils/format'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const submitting = ref(false)
const pendingRequests = ref([])
const approvalFormRef = ref(null)

// 搜索表单
const searchForm = reactive({
  itemName: '',
  requesterName: '',
  dateRange: []
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 审批对话框
const approvalDialog = reactive({
  visible: false,
  type: '',
  requestId: null
})

// 审批表单
const approvalForm = reactive({
  comment: ''
})

// 审批表单验证规则
const approvalRules = {
  comment: [
    { 
      required: approvalDialog.type === 'REJECTED', 
      message: '拒绝申请时必须填写审批意见', 
      trigger: 'blur' 
    }
  ]
}

// 获取待审批列表
const fetchPendingRequests = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      itemName: searchForm.itemName || undefined,
      requesterName: searchForm.requesterName || undefined
    }
    
    // 如果有日期范围，添加到参数中
    if (searchForm.dateRange && searchForm.dateRange[0] && searchForm.dateRange[1]) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    console.log('搜索参数:', params)
    
    const response = await getPendingPurchaseRequests(params)
    
    // 处理申请人数据映射
    pendingRequests.value = response.content.map(item => {
      return {
        ...item,
        requesterName: item.requestUser ? item.requestUser.name : '未知'
      }
    })
    
    total.value = response.totalElements
  } catch (error) {
    console.error('获取待审批列表失败:', error)
    ElMessage.error('获取待审批列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1  // 搜索时重置到第一页
  fetchPendingRequests()
}

// 重置搜索
const resetSearch = () => {
  searchForm.itemName = ''
  searchForm.requesterName = ''
  searchForm.dateRange = []
  currentPage.value = 1  // 重置到第一页
  fetchPendingRequests()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1  // 重置到第一页
  fetchPendingRequests()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPendingRequests()
}

// 查看详情
const viewDetail = (id) => {
  router.push(`/purchase-requests/${id}`)
}

// 处理审批操作
const handleApproval = (request, type) => {
  approvalDialog.visible = true
  approvalDialog.type = type
  approvalDialog.requestId = request.id
  approvalForm.comment = ''
}

// 提交审批
const submitApproval = async () => {
  if (approvalDialog.type === 'REJECTED') {
    // 拒绝时验证表单
    await approvalFormRef.value.validate()
  }
  
  submitting.value = true
  try {
    const data = {
      approved: approvalDialog.type === 'APPROVED',
      comment: approvalForm.comment
    }
    
    await approvePurchaseRequest(approvalDialog.requestId, data)
    ElMessage.success('审批操作成功')
    approvalDialog.visible = false
    fetchPendingRequests()
  } catch (error) {
    console.error('审批操作失败:', error)
    ElMessage.error('审批操作失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchPendingRequests()
})
</script>

<style scoped>
.approval-list {
  padding: 20px;
  height: calc(100vh - 120px);
  overflow: hidden;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  white-space: nowrap;
}

.form-row {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
}

.el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.button-item {
  margin-right: 0;
}

.date-picker {
  width: 260px;
}

.el-table {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 